<% layout('device_header') -%>




<div class="row">
	<div class="span3 pull-right" style="margin-right:100px">
			<button id="deleteAccount" onClick="generate()" class="btn btn-danger">
  				<i class="icon-trash icon-white"></i> Delete Accout
			</button>
			<br/><br/><br/>
			<textarea class="input-xlarge" id="message" rows="3" placeholder="Maximum 200 characters."></textarea>
			<button type="submit" id="sendmessage" onClick="sendMessage()" class="btn btn-success">
			<i class="icon-envelope icon-white"></i> Send Message to All</button>
	</div>

    <div class="span10 pull-left offset1">    
    	 <h1>My Devices</h1> <br/>	        
         <input type="text" id="name" name="name" class="input search-query" placeholder="Name"> <br/><br/>
         <input type="tel" id="device" name="device" class="input search-query" placeholder="Phone number">         
         <br/> <br/>
		 <select id="countrycode" name="countrycode">
		 <option value="1" selected>USA (+1) 
		 <option value="54">Argentina (+54) 
		 <option value="61">Australia (+61) 
		 <option value="43">Austria (+43) 
		 <option value="32">Belgium (+32) 
		 <option value="55">Brazil (+55) 
		 <option value="855">Cambodia (+855) 
		 <option value="237">Cameroon (+237) 
		 <option value="1">Canada (+1) 
		 <option value="56">Chile (+56) 
		 <option value="86">China (+86) 
		 <option value="57">Colombia (+57) 
		 <option value="45">Denmark (+45) 
		 <option value="2463">Diego Garcia (+2463) 
		 <option value="358">Finland (+358) 
		 <option value="33">France (+33) 
		 <option value="594">French Guiana (+594) 
		 <option value="689">French Polynesia (+689) 
		 <option value="7880">Georgia (+7880) 
		 <option value="49">Germany (+49) 
		 <option value="30">Greece (+30) 
		 <option value="299">Greenland (+299) 
		 <option value="852">Hong Kong (+852) 
		 <option value="36">Hungary (+36) 
		 <option value="354">Iceland (+354) 
		 <option value="91">India (+91) 
		 <option value="62">Indonesia (+62) 
		 <option value="81">Japan (+81) 
		 <option value="850">Korea North (+850) 
		 <option value="82">Korea South (+82) 
		 <option value="965">Kuwait (+965) 
		 <option value="856">Laos (+856) 
		 <option value="60">Malaysia (+60) 
		 <option value="960">Maldives (+960) 
		 <option value="52">Mexico (+52) 
		 <option value="31">Netherlands (+31) 
		 <option value="64">New Zealand (+64) 
		 <option value="47">Norway (+47) 
		 <option value="63">Philippines (+63) 
		 <option value="48">Poland (+48) 
		 <option value="351">Portugal (+351) 
		 <option value="7">Russia (+7) 
		 <option value="966">Saudi Arabia (+966) 
		 <option value="65">Singapore (+65) 
		 <option value="27">South Africa (+27) 
		 <option value="34">Spain (+34) 
		 <option value="94">Sri Lanka (+94) 
		 <option value="46">Sweden (+46) 
		 <option value="41">Switzerland (+41) 
		 <option value="886">Taiwan (+886) 
		 <option value="66">Thailand (+66) 
		 <option value="90">Turkey (+90) 
		 <option value="44">UK (+44) 
		 <option value="971">United Arab Emirates (+971) 
		 <option value="1">USA (+1) 
		 <option value="379">Vatican City (+379) 
		 <option value="84">Vietnam (+84) 
		 </select> <br/>
  		 <button id="add_device" class="btn btn-success" onClick="addDevicePost()" data-loading-text="Adding Device..."><i class="icon-plus-sign icon-white"></i>Add Device</button> 	   		 
        <br/> <br/>
        

	  <table id="devicetable" class="table">
	    <tbody id="devicetablebody">
			<% for(var i=0; i<devices.length; i++) {%>
			   <tr id="row_<%= devices[i].id%>">
			   	<td style="border-top:none">
			   		<div class="row well" >
				   		<h3 id="name"> <%= devices[i].name %> </h3> 
				   		<h4 id="phonenumber"> <%= devices[i].phonenumber %> </h4>
				   		<% if (devices[i].authenticated == 0) { %>
				   			<button type="button" class="btn btn-small btn-danger disabled" disabled="disabled"><i class="icon-remove icon-white"></i> Not Authenticated</button>
				   		<% } else { %>
							<button type="button" class="btn btn-small btn-success disabled" disabled="disabled"><i class="icon-ok icon-white"></i>Authenticated</button>
				   		<% } %>
				   		
				   		<button type="button" class="btn btn-small btn-primary"><i class="icon-envelope icon-white"></i>Send Access Code</button>
				   		<div class="pull-right">
				   			<a class="btn" id="map" href="/device/<%= devices[i].id%>" > <i class="icon-large icon-map-marker"></i></a>
				   			<a class="btn" id="delete" onClick="deleteDevice(<%= devices[i].id%>)"><i class="icon-large icon-trash"></i></a>				   			
				   		</div>
			   		</div>
			   	</td>
			   </tr>
			<% } %>
	    </tbody>
	  </table>
	  </div>
	  </div>

	<div id="deldevicemodal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	      <div class="modal-header">
	        <h3>Delete Device</h3>
	      </div>
	      <div class="modal-body">
	        <p> Are you sure want to delete the device.? </p>		        
	      </div>
		 <div class="modal-footer">
			<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Close</button>
  			<button " class="btn btn-danger yesBtn">Yes</button>		 
	    </div>	      
    </div>    

	<div id="delaccountmodal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	      <div class="modal-header">
	        <h3>Delete Device</h3>
	      </div>
	      <div class="modal-body">
	        <p> Are you sure want to delete the account.? </p> <small style="color:red">This action cannot be undone. </small> </div>
		 <div class="modal-footer">
			<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Close</button>
  			<button class="btn btn-danger yesBtn">Yes</button>		 
	    </div>	      
    </div>  

	<div id="alertmodal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	      <div class="modal-header">
	        <h3>Delete Device</h3>
	      </div>
	      <div id="alertbody" class="modal-body">

	      </div>
		 <div class="modal-footer">
  			<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">OK</button>	 
	    </div>	      
    </div> 

<script type="text/javascript">


$('#error').hide();

showAlert = function(msg) {
	$('#alertbody').html('<p>'+msg+'</p>');
	$('#alertmodal').modal('show');
}

addDevice = function(id) {	

	var html = '<tr id="row_"' +id+ '"><td style="border-top:none"><div class="row well">'+
				'<h3>'+$('#name').val()+'</h3> '+
				'<h4>'+ $('#device').val()+'</h4>'+
				'<button type="button" class="btn btn-small btn-danger disabled" disabled="disabled"><i class="icon-remove icon-white"></i> Not Authenticated</button>'+
				'<button type="button" class="btn btn-small btn-primary"><i class="icon-envelope icon-white"></i>Send Access Code</button>'+
				'<div class="pull-right">'+
				'<a class="btn" href="/device/'+id+'"> <i class="icon-large icon-map-marker"></i></a>'+
				'<a class="btn" id="'+id+'" onClick="deleteDevice(this.id)"><i class="icon-large icon-trash"></i></a>'+
				'</div></div></td></tr>';
	//$('#devicetable tr:last').after(html);
	//$('#devicetable tbody').append(html);
	var $tr = $('#devicetable').find("tbody tr:last").clone();
	$tr.attr("id","row_"+id);
	$tr.find("#name").text($('#name').val());
	$tr.find("#phonenumber").text($('#device').val());
	$tr.find("#map").attr("href","/device/"+id);
	$tr.find('#delete').attr("id",id);
	//TODO: click event is not registered properly. 
	$tr.find('#delete').click(function(id){
		alert('MANI DELETE '+id);
	});
	$('#devicetable').find("tbody tr:last").after($tr); 

	$('#device').val('');
    $('#name').val('');
    $('#countrycode').val('1');
}

//$("#device_form").submit(function(event){
submit_addDevice = function() {
	$('#error').hide();

    $("#name").attr("disabled", "disabled");
	$("#device").attr("disabled", "disabled");
	$("#countrycode").attr("disabled", "disabled");
	$("#add_device").attr("disabled", "disabled");

    // fire post request to /device
    $.ajax({
        url: "/device",
        type: "post",
        data: { 
        	'name': $("#name").val(), 
  			'device': $("#device").val(), 
  			'countrycode': $("#countrycode").val()
		},
        success: function(response, textStatus, jqXHR){
            // log a message to the console
            if( response.code) {
            	$('#error').show();
            	if( response.code == 'ER_DUP_ENTRY') {
            		$('#error').html('ERROR:Number already added');
            	} else {
            		$('#error').html('ERROR:Unable to add device');
            	}
            } else {
            	 // Add the entry to table, if success.
            	 addDevice(response);
            }
            $('#add_device').button('reset');
        },
        error: function(jqXHR, textStatus, errorThrown){
        	alert(" Error while submitting post "+testStatus+"  : "+errorThrown);
        },
        complete: function(){
            // enable the inputs
            $("#name").removeAttr("disabled");
            $("#device").removeAttr("disabled");
            $("#countrycode").removeAttr("disabled");
            $("#add_device").removeAttr("disabled");
        }
    });// End of ajax.
}

addDevicePost = function(){

    var phonenumber = $("#device").val();    
	if( ! $('#name').val() ) {
		showAlert('Please enter a name');
		return;
    } else if( ! $('#device').val() ) {
        showAlert('Please enter a valid phone number');
        return;
    } if( !(phonenumber.length >= 8 && phonenumber.length <= 10 )) {
        showAlert('Invalid Phonenumber');
        return;
    } else {
    	$('#add_device').button('loading');
    	submit_addDevice();
    }
}


deleteDevice = function(id) {

	var deviceId = id;
	$('#deldevicemodal').modal('show');

    // fire post request to /device
	$('#deldevicemodal .yesBtn').click(function() {  
		$('#deldevicemodal').modal('hide'); 	
	    $.ajax({
	        url: "/device/"+id,
	        type: "delete",
	        success: function(response, textStatus, jqXHR){
	            // log a message to the console
	            if( response.code) {
	            	alert('Error while deleting.');
	            } else {
	            	 // Success remove the entry.
	            	 $("#row_"+id).remove();
	            }
	        },
	        error: function(jqXHR, textStatus, errorThrown){
	        	alert(" Error while submitting post "+testStatus+"  : "+errorThrown);
	        },
	        complete: function(){
	            // enable the inputs
	        }
	    }); // End of ajax
    });
}

generate = function() {
	
}

deleteAccount = function() {
	$('#delaccountmodal').modal('show');
	$('#delaccountmodal .yesBtn').click(function() {   
		$('#delaccountmodal').modal('hide'); 
	    $.ajax({
	        url: "/user",
	        type: "delete",
	        success: function(response, textStatus, jqXHR){
	            // log a message to the console
	        },
	        error: function(jqXHR, textStatus, errorThrown){
	        },
	        complete: function(){
	            // enable the inputs
	        }
	    }); // End of ajax	
    });
}

sendMessage = function() {

	var devicesCount = <%= devices.length %>;

	if( length == 0){
		alert('No devices registered');
		return;
	}

	var pushMessage = $("#message").val();
	var userId = <%= user_id%>; 
	alert('send message');	
	$.ajax({
	        url: "/devices/push_message_to_all",
	        data: { 
	        	'user_id': userId, 
      			'push_message': pushMessage        		
    		},
	        type: "post",
	        success: function(response, textStatus, jqXHR){
	            // log a message to the console
	            alert(response);
	        },
	        error: function(jqXHR, textStatus, errorThrown){
	        	alert(" Error while sending push message "+testStatus+"  : "+errorThrown);
	        },
	        complete: function(){
	            // enable the inputs
	        }
	}); // End of ajax
}

</script>

